package it.polimi.swKnights.SWIMv2.servlets.users;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.AlreadyAskedException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.AlreadyFriendsException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.SelfFriendException;
import it.polimi.swKnights.SWIMv2.ejb.friendsEngine.FriendshipRequestManagerRemote;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;

import javax.ejb.EJBException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class FriendshipRequestProcessData
 */
public class FriendshipRequestProcessData extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("userName");
		String password = (String) session.getAttribute("password");

		String newFriend = (String) request.getParameter("newFriend");

		boolean direct = getDirect(request);

		FriendshipRequestManagerRemote friendshipRequestManager = this
				.lookUp(FriendshipRequestManagerRemote.class);

		try
		{
			friendshipRequestManager.askFriendship(newFriend, direct, userName,
					password);
			response.sendRedirect("./addFriends?sentTo=" + newFriend);
		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.session);
		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.session);
		}
		catch (EJBException e)
		{
			response.sendRedirect("./addFriends?error=" + Errors.notfound);
		}
		catch (SelfFriendException e)
		{
			response.sendRedirect("./addFriends?error=" + Errors.selffriend);
		}
		catch (AlreadyAskedException e)
		{
			response.sendRedirect("./addFriends?error=" + Errors.yetasked);
		}
		catch (AlreadyFriendsException e)
		{
			response.sendRedirect("./addFriends?error=" + Errors.alreadyfriends);
		}
	}

}
